﻿@using Sample.Models
@page "/"
@inject Context Context

<h1>BlazorDB Demo Site</h1>

<BSButton Color="Color.Primary" @onclick="@OnclickAddPerson">Add Person</BSButton>

<BSButton Color="Color.Primary" @onclick="@onclickRemovePerson">Remove Person</BSButton>

<BSButton Color="Color.Primary" @onclick="@OnclickGetPerson">Get Person</BSButton>

<BSButton Color="Color.Primary" @onclick="@OnclickSaveChanges">SaveChanges</BSButton>

<h2>Validations</h2>

<BSButton Color="Color.Primary" @onclick="@OnRequired">Required</BSButton>

<BSButton Color="Color.Primary" @onclick="@OnMaxLength">Max Length</BSButton>

@if (@Person != null)
{
    <div>
        Person: @Person.FirstName @Person.LastName
    </div>
}

@functions {
    private Person Person { get; set; }
    protected async override Task OnInitAsync()
    {
        await Context.Initialize();
    }
    void OnclickAddPerson()
    {
        //In this case, address gets serailized as part of the object because Address is not in the Context
        var person = new Person { FirstName = "John", LastName = "Smith", HomeAddress = new Address { Street = "221 Baker Street", City = "This should be part of the json, since address is not in context (Very long city)" } };
        var address1 = new Address { Street = "Many test 1", City = "Saved as a reference" };
        var address2 = new Address { Street = "Many test 2", City = "Saved as a reference" };
        person.OtherAddresses = new List<Address> { address1, address2 };
        Context.People.Add(person);
    }

    void onclickRemovePerson()
    {
        var query = from person in Context.People
                    where person.Id == 1
                    select person;
        var personToRemove = query.Single();
        Context.People.Remove(personToRemove);
    }

    void OnclickGetPerson()
    {
        var query = from person in Context.People
                    where person.Id == 1
                    select person;
        Person = query.Single();
        StateHasChanged();
    }

    async void OnclickSaveChanges()
    {
        await Context.SaveChanges();
    }

    void OnRequired()
    {
        var person = new Person { LastName = "Firstname required!" };
        Context.People.Add(person);
        Context.SaveChanges();
    }

    void OnMaxLength()
    {
        var person = new Person { FirstName = "Lastname is long", LastName = "This is a very long last name and should throw!" };
        Context.People.Add(person);
        Context.SaveChanges();
    }
}